<template>
  <div class="sysPageOptionConfigColumn-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }" >
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-if="props.info.id==undefined||props.info.id<=0">
        <el-form-item label="关键字">
          <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字"/>
          
        </el-form-item>
        <el-form-item label="路由路径">
          <el-input v-model="queryParams.configPath" clearable="" placeholder="请输入路由路径"/>
          
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'sysPageOptionConfigColumn:page'"> 查询 </el-button>
            <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
            
          </el-button-group>
          
        </el-form-item>
      </el-form>
        <el-col :span="24">
        <el-form-item>
         <el-button  type="primary" icon="ele-StarFilled"  @click="opensaveConfig">保存配置</el-button>
        </el-form-item>
        </el-col>
        
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 8px">
      <el-table
				:data="tableData"
				style="width: 60%"
				v-loading="loading"
				tooltip-effect="light"
				row-key="id"
				:key="forceUpdate"
				border=""
                ref="multipleTableRef" 
                :row-class-name="tableRowClassName"
                @select="handleSelectionChange" :expand-row-keys="expandList"
				@expand-change="handleExpandChange">
        <el-table-column type="selection" align="center" :selectable="checkTable"/>
        <el-table-column type="index" label="序号" width="55" align="center">
          <template #default="scope">
       </template>
       </el-table-column>
        <el-table-column prop="label" label="列描述" width="140" fixed="left" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input v-model="scope.row.label" placeholder="列描述" maxlength="53"/>
          </template>
        </el-table-column>
        <el-table-column prop="width" label="列宽" width="140" fixed="left" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input-number v-model="scope.row.width" placeholder="列宽" maxlength="53"/>
        </template>
        </el-table-column>
        <el-table-column prop="hide" label="隐藏列" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.hide" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="search" label="是否是搜索框" width="90" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.search" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="disabled" label="禁用" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.disabled" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="cell" label=" 列表中可编辑" width="105" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.cell" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="searchLabelWidth" label="搜索框宽度" width="140" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input-number v-model="scope.row.searchLabelWidth" placeholder="搜索框宽度" maxlength="53"/>
        </template>
        </el-table-column>
        <el-table-column prop="order" label="位置排序，数字越小位置越靠前" width="210" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input-number v-model="scope.row.order" placeholder="位置排序，数字越大位置越靠前" maxlength="53"/>
        </template>
        </el-table-column>
        <el-table-column prop="display" label="编辑隐藏" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.display" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="overHidden" label=" 列内容超出隐藏" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.overHidden" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="fixed_" label="固定列" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.fixed_" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="sortable" label="排序" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.sortable" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="span" label="编辑/新增表单列数" width="135" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input-number v-model="scope.row.span" placeholder="编辑/新增表单列数" maxlength="53"/>
        </template>
        </el-table-column>
        <el-table-column prop="labelTip" label="标题提示语" width="140" show-overflow-tooltip="" >
         <template #default="scope">
        <el-input v-model="scope.row.labelTip" placeholder="标题提示语" maxlength="53"/>
          </template>
        </el-table-column>
        <el-table-column prop="addDisplay" label="新增时是否显示" width="105" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.addDisplay" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="editDisplay" label="编辑时是否显示" width="105" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.editDisplay" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column prop="showWordLimit" label="显示字数限制" width="90" show-overflow-tooltip="">
          <template #default="scope">
            <el-switch v-model="scope.row.showWordLimit" active-text="是" inactive-text="否" />
            
          </template>
          
        </el-table-column>
        <el-table-column label="操作" :width="getWidthByAuths([])" align="center" fixed="right" show-overflow-tooltip="" v-if="auths([])">
          <template #default="scope">
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100, 200]"
				small=""
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper,->,"
	/>
    	<!-- 上面分页加上这个字符串就居中显示了 ->, -->
      <editDialog
        ref="editDialogRef"
        :title="editSysPageOptionConfigColumnTitle"
        @reloadTable="handleQuery"
      />
     <saveConfig title="保存配置" :key="timer" ref="saveConfigRef"  @reloadTable="handleQuery"/>
    </el-card>

    		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
						<ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action=""
					:on-change="handleChange" accept=".xls,.xlsx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>

        <el-dialog v-model="state.dialogInfoVisible" draggable width="1000px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Document /> </el-icon>
					<span>详情</span>
				</div>
			</template>
			<json-viewer :value="JSON.parse(state.dialogInfoContent)" :expand-depth="8"  copyable boxed sort></json-viewer>
		</el-dialog>

  </div>
</template>

<script lang="ts" setup="" name="sysPageOptionConfigColumn">
  import { ref,reactive,onMounted,nextTick } from "vue";
  import { useRoute } from 'vue-router';
  import { ElMessageBox, ElMessage,UploadInstance } from "element-plus";
  import _ from 'lodash';
  import { auth,getWidthByAuths,auths } from '/@/utils/authFunction';
  import { downloadByData, getFileName } from '/@/utils/download';
  //import { formatDate } from '/@/utils/formatTime';

  import editDialog from '/@/views/main/sysPageOptionConfigColumn/component/editDialog.vue'
   import saveConfig from '/@/views/main/sysPageOptionConfigColumn/component/saveConfig.vue'

  import { pageSysPageOptionConfigColumn,saveSysPageOptionConfigColumn, deleteSysPageOptionConfigColumn,exportSysPageOptionConfigColumnExcel } from '/@/api/main/sysPageOptionConfigColumn';
  import { SysFile } from '/@/api-services/models';
  import request from '/@/utils/request';
  	const uploadRef = ref<UploadInstance>();
	const state = reactive({
		loading: false,
		fileData: [] as Array<SysFile>,
		queryParams: {
			fileName: undefined,
			startTime: undefined,
			endTime: undefined,
		},
		tableParams: {
			page: 1,
			pageSize: 10,
			total: 0 as any,
		},
		dialogUploadVisible: false,
		dialogPdfVisible: false,
        dialogInfoVisible:false,
        dialogInfoContent:'',
		fileList: [] as any,
		pdfUrl: '',
	});
  const timer=ref<any>();
  const expandList = ref<any>([]);
  const editDialogRef = ref();
  const saveConfigRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const multipleTableRef = ref<InstanceType<typeof ElTable>>();
  const multipleSelection = ref<any>([]);
  const toggleSelection = (rows ?: []) => {
	 multipleTableRef.value.clearSelection()
  }
  const queryParams = ref<any>({});
  const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  frontPath:null
  });
  const editSysPageOptionConfigColumnTitle = ref("");
  const currenTab=ref<any>({});
   const tabOption =null;
  
  var props = defineProps({
		info: {
		default: {},
	},
  });
  
  const elTableRef = ref();
  const forceUpdate = ref(0);
  const setSort = () => {
      const el = multipleTableRef?.value?.$el.querySelector('.el-table__body-wrapper tbody')
  	console.log(el)
      new Sortable(el, {
          animation: 180,
          delay: 0,
  		ghostClass: 'sortable-ghost', //拖拽样式
  		easing: 'cubic-bezier(1, 0, 0, 1)',
  		onEnd: function({oldIndex, newIndex}){
  		const arr = tableData.value;
  	// 		if(arr===undefined){
			// 	return;
			// }
			console.log(arr);
  			const currentRow = arr.splice(oldIndex, 1)[0]
  			arr.splice(newIndex, 0, currentRow )
  			tableData.value = [];
  			nextTick(async () => {
  				tableData.value = arr;
  				for (let index = 0; index < tableData.value.length; index++) {
  					const element = tableData.value[index];
  					element.order = index + 1;
  					//console.log(element.FieldName + "========" + element.OrderBy);
  				}
  				
  			});
  		},
          // 列表内元素顺序更新的时候触发
          onUpdate: function (/**Event*/evt) {
  
          },
      })
  }
    // 页面加载时
  onMounted(async () => {
	  const route=useRoute();
	  tableParams.value.frontPath=route.path;
      handleQuery();
      if(tabOption!=null){
      currenTab.value=tabOption.column[0];
      }
  });
  const selectAfter=()=>{
     nextTick(()=>{
        });
	}
    //页签切换
    const handleTabChange =(column)=> {
        currenTab.value = column;
         selectAfter();
    }
  // 勾选框是否禁用

     const checkTable=(row,index)=>{
     if(row.id){
		return true; //不禁用
        }
		return false; //禁用
     };

     //行颜色
      const tableRowClassName = (every) =>
      {
      }

  	// 打开上传页面
	const openUploadDialog = () => {
		state.fileList = [];
		state.dialogUploadVisible = true;
	};

	// 通过onChanne方法获得文件列表
	const handleChange = (file : any, fileList : []) => {
		state.fileList = fileList;
	};

    //保存行编辑的数据
   const saveData=  _.debounce(async function (row) {
		await saveSysPageOptionConfigColumn(row);
		await handleQuery();
	}, 1000);
   

    // 查看详情
    const viewDetail =_.throttle(async (row: any,tableName:string,id:number) => {
    	var url = `api/sysPageOptionConfigColumn/Info/${tableName}/${id}`
    	var res = await request({url: url,method: 'get'});
    	state.dialogInfoContent=res.data.result;
    	state.dialogInfoVisible = true;
    },1000);

	// 上传
	const uploadFile = async () => {
		if (state.fileList.length < 1) return;
		var url = `api/sysPageOptionConfigColumn/Import`

		var formData = new window.FormData();
		formData.append('file', state.fileList[0].raw);
		var res = await request(
			{
				url: url,
				method: 'post',
				data: formData,
				headers: { 'Content-Type': 'multipart/form-data' }
			}
		)
		ElMessage.success('上传成功');
		await handleQuery();
		state.dialogUploadVisible = false;
	};

  //导出
    const exportSysPageOptionConfigColumn=async()=>{
	   var res =await exportSysPageOptionConfigColumnExcel(queryParams.value);
	   var fileName = getFileName(res.headers);
	   downloadByData(res.data as any, fileName);
   };

   //下载模板
   	const downLoadTemplate = async () => {
		var url = `api/sysPageOptionConfigColumn/TemplateDown`
		var res = await request({
			url: url,
			method: 'get',
			responseType: 'blob'
		});
		var fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
	}

  // 查询操作
  const handleQuery = async (parentArgument:any) => {
    timer.value = new Date().getTime();
    loading.value = true;
    if(props.info.id>0){
     // queryParams.value.standardId = props.info.id; //展开行对应的id赋值
     queryParams.value.configPath = props.info.configPath; 
    }
    if(parentArgument!=null&&parentArgument!=undefined){
	  if(parentArgument.id==-1){
		 queryParams.value.wCode = parentArgument.id; //此页作为组件，parentArgument父组件传过来的值
	  }else{
		 queryParams.value.wCode = parentArgument.wCode; //此页作为组件，parentArgument父组件传过来的值
	  }
	}
    var res = await pageSysPageOptionConfigColumn(Object.assign(queryParams.value, tableParams.value));
    tableData.value = res.data.result?.items ?? [];
    tableParams.value.total = res.data.result?.total;
    loading.value = false;
	setSort();
  };

  // 打开新增页面
  const openAddSysPageOptionConfigColumn = () => {
    editSysPageOptionConfigColumnTitle.value = '添加页面配置明细';
    editDialogRef.value.openDialog({});
  };

  // 打开编辑页面
  const openEditSysPageOptionConfigColumn = (row: any) => {
    editSysPageOptionConfigColumnTitle.value = '编辑页面配置明细';
    editDialogRef.value.openDialog(row);
  };

      const opensaveConfig=_.debounce((row:any)=>{
	saveConfigRef.value.commentClick(tableData,props.info);},1000);

   	const showKeyValueInfo=(list)=>{
		if(list!=null&&list.length>0){
			if(list[0].label!=undefined){
				return list.map(r => r.label)
			}
		}
		return list;
	}
  

  	const handleExpandChange = (row : any, expandedRows : any) => {
		 timer.value = new Date().getTime();
		if (expandedRows.length) {
			expandList.value = [];
			if (row) {
				expandList.value.push(row.id);
			}
		} else {
			expandList.value = [];
		}
	};

  // 删除
  const delSysPageOptionConfigColumn = (row: any) => {
    ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async () => {
    await deleteSysPageOptionConfigColumn(row);
    handleQuery();
    ElMessage.success("删除成功");
  })
  .catch(() => {});
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

  
   const handleSelectionChange = (val: any) => {
     multipleSelection.value = val;
     selectAfter();
   }



	//将属性或者函数暴露给父组件
   defineExpose({ handleQuery });
</script>
<style scoped lang='scss'>
@import url('../../../../public/css/iconfont.css');
@import url('../../../../public/css/iconshine.css');
@import url('../../../../public/css/linecolor.css');
</style>

